﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using RuoVea.ExFilter.Language;

namespace RuoVea.ExFilter;

/// <summary>
/// 对结果进行统一
/// </summary>
public class ResultFilter : Attribute, IResultFilter
{
    private readonly IRESTfulResult _restfulResult;

    /// <summary>
    /// 构造
    /// </summary>
    /// <param name="restfulResult"></param>
    public ResultFilter(IRESTfulResult restfulResult)
    {
        _restfulResult = restfulResult;
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    public void OnResultExecuted(ResultExecutedContext context) { }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    public void OnResultExecuting(ResultExecutingContext context)
    {
        if (context.IsNonRestfulResult()) return;
        object data;
        int statusCode = 200;
        switch (context.Result)
        {
            // 处理内容结果
            case ContentResult contentResult:
                data = contentResult.Content;
                statusCode = contentResult.StatusCode ?? 200;
                break;
            // 处理对象结果
            case ObjectResult objectResult:
                data = objectResult.Value;
                statusCode = objectResult.StatusCode ?? 200;
                break;
            case EmptyResult:
                data = null;
                break;
            default:
                return;
        }
     
        object result;
        CodeStatus codeStatus = Enum.TryParse(typeof(CodeStatus), statusCode + "", out result) == true ? result == null ? CodeStatus.OK : (CodeStatus)result : CodeStatus.OK;
       
        var restfulResult = _restfulResult.RESTfulResult(codeStatus, data, codeStatus == CodeStatus.OK ? i18n.requestsuccess :i18n.requestfailure);

        context.Result = new JsonResult(restfulResult);
    }
}
